//
//  JDTabBar.m
//  JD_Project_OC
//
//  Created by snowimba on 16/1/29.
//  Copyright © 2016年 snowimba. All rights reserved.
//

#import "JDTabBar.h"

@interface JDTabBarButton : UIButton

@end

@implementation JDTabBarButton

- (void)setHighlighted:(BOOL)highlighted
{
    //    [super setHighlighted:highlighted];
}

@end

@interface JDTabBar ()

@property (nonatomic, weak) UIButton* currentButton;

@end

@implementation JDTabBar

- (void)addButtonWithImage:(UIImage*)image andImageSel:(UIImage*)imageSel andTitle:(NSString*)title
{
    // 创建 btn
    JDTabBarButton* tabbarButton = [[JDTabBarButton alloc] init];

    // 设置 btn 的图片
    [tabbarButton setImage:image forState:UIControlStateNormal];
    [tabbarButton setImage:imageSel forState:UIControlStateSelected];
    [tabbarButton setTitle:title forState:UIControlStateNormal];
    tabbarButton.titleLabel.font = [UIFont systemFontOfSize:10.0];
    tabbarButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    tabbarButton.imageView.contentMode = UIViewContentModeCenter;
    [tabbarButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [tabbarButton setTitleColor:[UIColor colorWithRed:234 / 255.0 green:59 / 255.0 blue:66 / 255.0 alpha:1] forState:UIControlStateSelected];

    tabbarButton.titleEdgeInsets = UIEdgeInsetsMake(30, -73, 0, 0);
    tabbarButton.imageEdgeInsets = UIEdgeInsetsMake(-13, 0, 0, 0);

    // 监听 btn
    [tabbarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchDown];

    // 添加到自己上
    [self addSubview:tabbarButton];
}

// 点击 tabbar 上按钮的时候调用
- (void)tabBarButtonClick:(UIButton*)sender
{

    // 取消记录的按钮的选中状态
    self.currentButton.selected = NO;

    // 设置点击的按钮为选中状态
    sender.selected = YES;

    // 记录选中的按钮
    self.currentButton = sender;

    // 切换控制器
    //    self.selectedIndex = sender.tag;
    // 判断 block 是否有值(代理方法 是不是能够响应)
    if (self.tabbarButtonBlock) {
        // 2.执行 block(执行代理方法)
        self.tabbarButtonBlock(sender.tag);
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    for (int i = 0; i < self.subviews.count; ++i) {

        // 获取 button
        UIButton* tabbarButton = self.subviews[i];

        // 设置 tag 切换控制器
        tabbarButton.tag = i;

        // 计算按钮的 frame
        CGFloat w = kScreenWidth / 5;
        CGFloat h = 50;
        CGFloat x = i * w;
        CGFloat y = 0;

        tabbarButton.frame = CGRectMake(x, y, w, h);

        // 点一下第一个按钮
        if (i == 0) {
            [self tabBarButtonClick:tabbarButton];
        }
    }
}

@end
